import axios, { AxiosInstance } from "axios";
import { ERROR_CODE } from "../config/status-code";
import { SYSTEM_CONFIG } from "/@/config/system";
import { messageErrorTip } from "./message-config";
import { clearAccessToken, getAccessToken } from "./common";
import { createWebRouter } from "../router";

const service: AxiosInstance = axios.create({
  timeout: 5000,
});

/**
 * token 超时后清理前端token信息 重置路由 并跳转登录页
 */
const tokenInvalidAfter = () => {
  //清除前端保存的token信息
  clearAccessToken();
  messageErrorTip("您的登录已失效,请重新登录");
  createWebRouter();
  location.reload();
};

// request interceptor 在方法请求前插入token
service.interceptors.request.use(
  (config) => {
    //写入token
    let token = getAccessToken();
    if (config.url !== SYSTEM_CONFIG.tokenUrl) {
      config.headers["Authorization"] = "bearer " + token;
    }
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => response,
  (error) => {
    const response = error.response;
    if (response.status == ERROR_CODE.SERVER_ERROR) {
      messageErrorTip("服务器异常：" + response.data.message || "系统内部异常");
    } else if (response.status == ERROR_CODE.UNAUTHORIZED) {
      tokenInvalidAfter();
      messageErrorTip("权限异常：无权限访问!");
    } else if (response.status == ERROR_CODE.NOT_FOUND_ERROR) {
      messageErrorTip("接口未找到：" + response.data.path);
    } else if (response.status == ERROR_CODE.UNAVAILABLE_ERROR) {
      messageErrorTip("服务器异常：" + "服务不可用");
    } else if (response.status == 400) {
      messageErrorTip("登录失败：" + "用户名或者密码错误！");
    } else {
      messageErrorTip("服务器异常：" + "系统错误!");
      console.log(error);
    }
    return Promise.reject(error);
  }
);

export default service;
